<template>
	<view>
		<view v-if="homeStore.isLoading && homeStore.data.length === 0" class="loading">
			<text>加载中，请稍候...</text>
		</view>

		<view class="content" v-else>
			<pm-header :title="homeStore.title" :sub-title="homeStore.subTitle"></pm-header>

			<pm-music-item class="item" :playing="homeStore.player.music && homeStore.player.music.name === music.name"
				v-for="music in homeStore.data" :music="music" @tap="onItemClick(music)" :key="music.name">
			</pm-music-item>

			<view class="footer">
				<text>以上都是世界名曲喔~</text>
			</view>

			<view v-if="homeStore.player.music" style="height: 180px; width: 100%;">

			</view>

			<pm-player v-if="homeStore.player.music" :paused="homeStore.player.paused"
				:currentTime="homeStore.player.currentTime" :duration="homeStore.player.duration"
				@onPlayClick="homeStore.play()" @onSeekClick="homeStore.seek($event)" @onPauseClick="homeStore.pause()"
				@onNextClick="homeStore.next()" @onLastClick="homeStore.last()" :name="homeStore.player.music?.name">
			</pm-player>
		</view>
	</view>
</template>

<script setup>
	import { useHomeStore } from '@/store/home.js'
	import { onLoad, onPullDownRefresh, onPageScroll } from '@dcloudio/uni-app'

	const homeStore = useHomeStore();

	onLoad((options) => {
		load();
	})

	function load(cb) {
		homeStore.load((err) => {
			if (err) {
				uni.showModal({
					showCancel: false,
					title: "错误",
					content: err.message
				})
			}

			if (cb) {
				cb(err);
			}
		})
	}

	onPullDownRefresh(() => {
		load(() => {
			uni.stopPullDownRefresh();
		})
	})

	onPageScroll(({ scrollTop }) => {
		if (scrollTop > 80) {
			uni.setNavigationBarTitle({
				title: uni.getSystemInfoSync().appName
			})
		} else {
			uni.setNavigationBarTitle({
				title: ""
			})
		}
	})

	function onItemClick(music) {
		if (homeStore.player.music && homeStore.player.music.name === music.name) {
			if (homeStore.player.paused) {
				homeStore.play();
			} else {
				homeStore.pause();
			}
			return;
		}
		homeStore.setMusic(music);
		homeStore.play();
	}
</script>

<style scoped lang="scss">
	.loading {
		width: 100%;
		height: 300px;
		font-size: 14px;
		color: #444444;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.content {
		display: flex;
		flex-direction: column;
		row-gap: 12px;

		.item {
			margin: 0 12px;
		}

		.footer {
			width: 100%;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			color: $uni-text-color-grey;
			font-size: 12px;
			padding-bottom: 60px;
		}
	}
</style>
